package org.elanfox.intellicommunity.intellicommunityadmin.boot;

import org.elanfox.intellicommunity.biz.entity.auth.SystemManager;
import org.elanfox.intellicommunity.biz.entity.auth.SystemMenu;
import org.elanfox.intellicommunity.biz.entity.auth.SystemRole;
import org.elanfox.intellicommunity.biz.repository.system.SystemManagerRepository;
import org.elanfox.intellicommunity.biz.repository.system.SystemMenuRepository;
import org.elanfox.intellicommunity.biz.service.core.auth.SystemService;
import org.elanfox.intellicommunity.biz.service.core.statistics.AlarmStatisticsService;
import org.elanfox.intellicommunity.common.ienum.RoleType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.Year;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author allan
 * @date 2018-08-06
 */
@Component
public class ApplicationBoot {

    @Autowired
    private SystemService systemService;
    @Autowired
    private SystemManagerRepository systemManagerRepository;

    @Autowired
    private SystemMenuRepository systemMenuRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    private SystemManager manager;

    @PostConstruct
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public void init() {
        initSystemManager();
        initSystemMenu();
        initStatistics();
    }

    /**
     * 初始化系统管理员
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void initSystemManager() {
        if (systemManagerRepository.count() == 0) {
            LocalDateTime dateTime = LocalDateTime.now();
            SystemRole role = new SystemRole();
            role.setEnable(true);
            role.setRoleName("超级管理员");
            role.setRoleType(RoleType.Default.getCode());
            role.setCreateTime(dateTime);
            role.setAuthority("");
            role.setUserId(-1);
            role = systemService.saveRole(role);
            manager = new SystemManager();
            manager.setRole(role);
            manager.setCreateTime(dateTime);
            manager.setLoginName("admin");
            manager.setEnable(true);
            manager.setParentUserId(0);
            manager.setLoginPwd(passwordEncoder.encode("123456"));
            manager.setLastLoginTime(dateTime);
            systemService.saveManager(manager);
        }

        manager = systemService.findManagerByLoginName("admin");
        if (manager != null) {
            manager.setLoginPwd(passwordEncoder.encode("root123"));
            systemService.saveManager(manager);
        }
    }

    @Autowired
    private AlarmStatisticsService alarmStatisticsService;

    private void initStatistics() {
        Year year = Year.now();
        //9月份
//        for (int i = 1; i <= Month.SEPTEMBER.maxLength(); i++) {
//            LocalDate date = LocalDate.of(year.getValue(), Month.JULY, i);
//            alarmStatisticsService.statistics(date);
//        }
        //10月份，统计到14号
        for (int i = 15; i <= Month.OCTOBER.maxLength(); i++) {
            LocalDate date = LocalDate.of(year.getValue(), Month.OCTOBER, i);
            alarmStatisticsService.statistics(date);
        }
        //11月份，统计到23号
        for (int i = 1; i <= 23; i++) {
            LocalDate date = LocalDate.of(year.getValue(), Month.NOVEMBER, i);
            alarmStatisticsService.statistics(date);
        }
    }

    /**
     * 初始化系统菜单
     */
    public void initSystemMenu() {
        List<SystemMenu> menuList = systemMenuRepository.findAll();
        if (menuList == null || menuList.size() == 0) {
            boolean isFunction = false;
            SystemMenu menu = saveMenu(0, "系统配置", 50, "none", "cogs", isFunction, null);
            Integer pid = menu.getItemCode();
            //功能权限
            Map<String, String> functionMap = new HashMap<>();
            functionMap.put("/sys/ajax/save", "添加和编辑");
            functionMap.put("/sys/ajax/list", "列表");
            functionMap.put("/sys/ajax/details", "详情");
            functionMap.put("/sys/ajax/activate", "设置状态");
            functionMap.put("/sys/ajax/delete", "删除");
            saveMenu(pid, "菜单管理", 2, "/sys/menus", "bars", isFunction, functionMap);

            functionMap.clear();
            functionMap.put("/sys/ajax/rolelist", "列表");
            functionMap.put("/sys/ajax/editrole", "添加和编辑");
            functionMap.put("/sys/ajax/deleterole", "删除");
            functionMap.put("/sys/ajax/setpower", "设置权限");
            functionMap.put("/sys/ajax/setenable", "设置状态");
            functionMap.put("/sys/ajax/list", "权限列表");
            saveMenu(pid, "角色管理", 3, "/sys/roles", "user", isFunction, functionMap);

            functionMap.clear();
            functionMap.put("/sys/ajax/editmanager", "添加和编辑");
            functionMap.put("/sys/ajax/managerlist", "列表");
            functionMap.put("/sys/ajax/setuserenable", "设置状态");
            saveMenu(pid, "账户管理", 4, "/sys/manager", "users", isFunction, functionMap);

            menu = saveMenu(0, "设备管理", 1, "none", "file-text-o", isFunction, null);
            pid = menu.getItemCode();
            functionMap.clear();
            functionMap.put("/equipment/ajax/save/card", "添加和编辑");
            functionMap.put("/equipment/edit/card/enable", "修改状态");
            saveMenu(pid, "卡列表", 1, "/equipment/card/list", "list", isFunction, functionMap);
            functionMap.clear();
            functionMap.put("/equipment/ajax/save/base/station", "添加和编辑");
            functionMap.put("/equipment/edit/base/station/enable", "修改状态");
            saveMenu(pid, "基站列表", 2, "/equipment/base/station/list", "list", isFunction, functionMap);
            functionMap.clear();
            functionMap.put("/equipment/ajax/save/locator", "添加和编辑");
            functionMap.put("/equipment/edit/locator/enable", "修改状态");
            functionMap.put("/equipment/locator/strId", "获取某一楼层的所有定位器");
            saveMenu(pid, "定位器列表", 2, "/equipment/locator/list", "list", isFunction, functionMap);

            menu = saveMenu(0, "用户管理", 1, "none", "file-text-o", isFunction, null);
            pid = menu.getItemCode();
            functionMap.clear();
            functionMap.put("/resident/ajax/save", "添加和编辑");
            saveMenu(pid, "住户列表", 1, "/resident/list", "list", isFunction, functionMap);
            functionMap.clear();
            functionMap.put("/resident/save/org", "添加和编辑");
            saveMenu(pid, "部门列表", 2, "/resident/org/list", "list", isFunction, functionMap);

            functionMap.clear();
            functionMap.put("/map/structure/tree", "获取社区树");
            functionMap.put("/map/user/list", "获取用户列表");
            functionMap.put("/map/location/msg", "获取最新一条定位消息");
            saveMenu(0, "设备打点", 2, "/map/add/point/page", "list", isFunction, functionMap);

            functionMap.clear();
            functionMap.put("/resident/structure/tree/data", "获取社区数据");
            functionMap.put("/resident/delete/structure", "删除社区");
            functionMap.put("/resident/save/structure", "新增/修改社区");
            saveMenu(0, "社区列表", 2, "/resident/structure/tree", "list", isFunction, functionMap);

//            functionMap.clear();
//            saveMenu(pid, "模板消息", 4, "/wxTemplate/list", "list", isFunction, functionMap);

//            functionMap.clear();
//            functionMap.put("/config/ajax/save", "编辑");
//            saveMenu(pid, "全局配置", 0, "/config/getConfig", "list", isFunction, functionMap);
//
//
//            functionMap.clear();
//            saveMenu(pid, "广告列表", 1, "/banner/list", "list", isFunction, functionMap);
//            functionMap.clear();
//            saveMenu(pid, "添加广告", 1, "/banner/edit", "edit", false, isFunction, functionMap);

//
//            menu = saveMenu(0, "文章管理", 49, "none", "file-text-o", isFunction, null);
//            pid = menu.getItemCode();
//            functionMap.clear();
//            functionMap.put("/article/ajax/articlelist", "列表");
//            saveMenu(pid, "文章列表", 1, "/article/list", "list", isFunction, functionMap);
//
//
//            functionMap.clear();
//            functionMap.put("/article/ajax/editarticle", "添加和编辑");
//            functionMap.put("/article/ajax/getarticleinfo", "详情");
//            saveMenu(pid, "添加文章", 2, "/article/edit", "pencil-square-o", false, isFunction, functionMap);
//
//            functionMap.clear();
//            functionMap.put("/article/ajax/classifylist", "列表");
//            functionMap.put("/article/ajax/editclassify", "添加和编辑");
//            functionMap.put("/article/ajax/deleteclassify", "删除");
//            saveMenu(pid, "文章分类", 3, "/article/classifylist", "list", isFunction, functionMap);


//            menu = saveMenu(0, "产品管理", 49, "none", "file-text-o", isFunction, null);
//            pid = menu.getItemCode();
//            functionMap.clear();
//            functionMap.put("/goods/ajax/goodslist", "列表");
//            functionMap.put("/goods/ajax/deletegoods", "删除");
//            functionMap.put("/goods/ajax/updategoodsstatus", "上架和下架");
//            saveMenu(pid, "产品列表", 1, "/goods/list", "list", isFunction, functionMap);
//            functionMap.clear();
//            functionMap.put("/goods/ajax/getgoodsinfo", "详情");
//            functionMap.put("/goods/ajax/editgoods", "添加和编辑");
//            saveMenu(pid, "添加产品", 2, "/goods/edit", "pencil-square-o", false, isFunction, functionMap);

//
//            menu = saveMenu(0, "用户管理", 48, "none", "users", isFunction, null);
//            pid = menu.getItemCode();
//            functionMap.clear();
//            functionMap.put("/userLevel/ajax/list", "列表");
//            saveMenu(pid, "等级列表", 1, "/userLevel/list", "list", isFunction, functionMap);
//            functionMap.clear();
//            saveMenu(pid, "奖金列表", 2, "/tempRebate/list", "list", isFunction, functionMap);
//            functionMap.clear();
//            saveMenu(pid, "基金列表", 3, "/fund/list", "list", isFunction, functionMap);

//            functionMap.clear();
//            saveMenu(pid, "用户列表", 3, "/user/list", "list", isFunction, functionMap);
//
//            menu = saveMenu(0, "订单管理", 47, "none", "users", isFunction, null);
//            pid = menu.getItemCode();
//            functionMap.clear();
//            saveMenu(pid, "零售订单", 1, "/order/retail/list", "list", isFunction, functionMap);
//            functionMap.clear();
//            saveMenu(pid, "发货管理", 2, "/order/retail/deliver/list", "list", isFunction, functionMap);
//            functionMap.clear();
//            saveMenu(pid, "批发订单", 3, "/order/wholesale/list", "list", isFunction, functionMap);
//            functionMap.clear();
//            menu = saveMenu(0, "交易管理", 48, "none", "list", isFunction, null);
//            pid = menu.getItemCode();
//            functionMap.clear();
//            saveMenu(pid, "挂卖列表", 1, "/deal/sell/list", "list", isFunction, functionMap);
//            functionMap.clear();
            //桌面
            saveMenu(0, "首页", 0, "/desktop", "desktop", isFunction, null);
        }
    }

    /**
     * 保存功能菜单
     *
     * @param pid
     * @param title
     * @param url
     */
    private void saveFunctionMenu(Integer pid, String title, String url) {
        saveMenu(pid, title, 1, url, "", true, null);
    }

    /**
     * 保存菜单
     *
     * @param pid
     * @param title
     * @param sort
     * @param url
     * @param iconCls
     * @return
     */
    private SystemMenu saveMenu(Integer pid, String title, int sort, String url, String iconCls, boolean isFunction, Map<String, String> functionMap) {
        return saveMenu(pid, title, sort, url, iconCls, true, isFunction, functionMap);
    }

    private SystemMenu saveMenu(Integer pid, String title, int sort, String url, String iconCls, boolean isEnable, boolean isFunction, Map<String, String> functionMap) {
        SystemMenu menu = new SystemMenu();
        menu.setCreateTime(LocalDateTime.now());
        menu.setItemParentCode(pid);
        menu.setItemEnable(isEnable);
        menu.setItemName(title);
        menu.setItemSort(sort);
        menu.setItemPath(url);
        menu.setItemIconCls(iconCls);
        menu.setItemFunction(isFunction);
        menu.setItemChildCount(Long.valueOf(0));
        systemService.save(menu);
        Integer itemCode = menu.getItemCode();
        if (functionMap != null) {
            functionMap.forEach((key, value) -> saveFunctionMenu(itemCode, value, key));
        }
        return menu;
    }
}
